﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xcj.Mes.Core.FileHelper;

namespace Xcj.Mes.Core.Logger
{
    public static class MyLogger
    {
        private static string CurrentDisk = Environment.CurrentDirectory?.Substring(0, 2);
        private static Encoding DefaultEncoding = Encoding.UTF8;
        private static object lockLog = new object();
        
        public static void Log(string filename, string text)
        {
            if(string.IsNullOrEmpty(filename?.Trim())) return;

            new Task((o) =>
            {
                lock (lockLog)
                {
                    try
                    {
                        var p = ((string filename, string text)?)o;
                        
                        if(p == null) return;

                        MyFileHelper.myFileHelper.Append($"{p?.filename}", p?.text, Encoding.GetEncoding("gb2312"));
                    }
                    catch { }
                }
            }, (filename?.Trim(), text)).Start();
        }

        public static void Log(Exception ex)
        {
            StackTrace st = new StackTrace(ex, true);

            if ((st?.FrameCount ?? 0) > 0)
            {
                try
                {
                    StackFrame[] stackFrames = st.GetFrames();
                    string Text = string.Empty;
                    foreach (var frame in stackFrames)
                    {
                        string filename = frame?.GetFileName() ?? string.Empty;
                        int linenumber = frame?.GetFileLineNumber() ?? 0;
                        string method = frame?.GetMethod()?.Name ?? string.Empty;
                        Text += $"【{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}】：文件 {filename} - 方法 {method} - 行号 {linenumber} : {ex.Message}\r\n";
                    }

                    if (!string.IsNullOrEmpty(Text.Trim()))
                        ExceptionLog(Text.Trim());
                }
                catch { }
            }
        }

        private static void ExceptionLog(string v)
        {
            string filename = $"{CurrentDisk}\\生产数据\\日志\\调试日志\\{DateTime.Now:yyyy年MM月dd日}\\ExceptionLog_{DateTime.Now:HH}.log";
            Log(filename, v);
        }

        public static void Log(string text)
        {
            string filename = $"{CurrentDisk}\\生产数据\\日志\\调试日志\\{DateTime.Now:yyyy年MM月dd日}\\Log_{DateTime.Now:HH}.log";
            text = $"【{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}】：{text}\r\n";
            Log(filename, text);
        }
    }
}
